package cn.seaboot.admin.rabbit.test;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * 发生 MQTT 消息
 *
 * @author Mr.css
 * @version 2024-10-15 9:16
 */
public class MqttPublish {

    public static void main(String[] args) throws Exception {
        try {
            String topic = "mqtt";
//            String broker = "tcp://localhost:1883";
//            String broker = "tcp://47.122.57.10:1883";
            String broker = "tcp://119.45.132.175:1883";
            String clientId = "MqttPublish";

            MqttClient client = new MqttClient(broker, clientId);

            // 使用自定义参数连接
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName("root");
            options.setPassword("root".toCharArray());
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            client.connect(options);

            int cnt = 10;
            while(cnt --> 0){
                String content = "Hello MQTT " + cnt;
                MqttMessage message = new MqttMessage(content.getBytes());
                message.setQos(2);
                message.setRetained(false);

                client.publish(topic, message);
                System.out.println("send: " + message);


                // 100 秒内可以重发消息
                Thread.sleep(5000);
            }

            // 100 秒内可以重发消息
            Thread.sleep(100_000);

            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}